package com.czkt.util;

import com.czkt.pojo.SsUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.userdetails.User;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.Key;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtils {

    private static final String SECRET_KEY = "11111111111111111111111111111111";

    public static String createToken(User user){
        SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes());
        Map<String, Object> claims = new HashMap<>();
        String token =  Jwts.builder().signWith(key)
                .setClaims(claims).setSubject(user.getUsername()).setIssuedAt(new Date())
                .expiration(new Date(System.currentTimeMillis() + 3600000))
                .compact();
        return token;
    }

    public static boolean validateToken(String token) {
        try {
            Jwts.parser().setSigningKey(SECRET_KEY).build().parseSignedClaims(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public static Claims parseToken(String token){
        SecretKey key = Keys.hmacShaKeyFor(SECRET_KEY.getBytes(StandardCharsets.UTF_8));

        Jws<Claims> result = Jwts.parser()
                .verifyWith(key)
                .build()
                .parseSignedClaims(token);

        return result.getPayload();
    }

}
